﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using MySql.Data.MySqlClient;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;

namespace Bluebunnie
{
    public static class DataManager
    {
        public static MySqlParameter[] ToMySqlParameter(this Parameter[] parameters)
        {
            return (from p in parameters select new MySqlParameter(p.Key, p.Value)).ToArray(); 
        }

        public static string ConnectionString { get; private set; }

        static DataManager()
        {
            ConnectionString = "server=localhost;user id=root;database=project";
        }

        public static DataTable GetData(string sql, params Parameter[] parameter)
        {
            return MySqlHelper.ExecuteDataset(ConnectionString, sql, parameter.ToMySqlParameter()).Tables[0];
        }

        public static LinkedDataTable GetDataWithAdapter(string sql, params Parameter[] parameter)
        {
            MySqlConnection connection = new MySqlConnection(ConnectionString);
            MySqlCommand command = new MySqlCommand(sql);
            
            foreach (Parameter param in parameter)
            {
                command.Parameters.AddWithValue(param.Key, param.Value);
            }

            MySqlDataAdapter adapter = new MySqlDataAdapter(command);
            DataTable table = new DataTable();

            adapter.Fill(table);

            return new LinkedDataTable(table, adapter);
        }

        public static T GetValue<T>(string sql, params Parameter[] parameter)
        {
            return (T)MySqlHelper.ExecuteScalar(ConnectionString, sql, parameter.ToMySqlParameter());
        }

        public static object GetValue(string sql, params Parameter[] parameter)
        {
            return GetValue<object>(sql, parameter);
        }

        public static int Execute(string sql, params Parameter[] parameter)
        {
            return MySqlHelper.ExecuteNonQuery(ConnectionString, sql, parameter.ToMySqlParameter());
        }

        public static List<ComboBoxItem> PopulateList(string sql, params Parameter[] param)
        {
            var cbl = new List<ComboBoxItem>();
            DataTable dt = GetData(sql, param);
            
            foreach (DataRow dr in dt.Rows)
            {
                cbl.Add(new ComboBoxItem { Content = dr.ItemArray[1], Tag = dr.ItemArray[2] });
            }

            return cbl;
        }

        public static object GetValue(this ComboBox cb)
        {
            if (cb.SelectedItem == null)
                return null;

            ComboBoxItem cbi = cb.SelectedItem as ComboBoxItem;
            if (cbi.Tag == null)
                return cbi.Content.ToString();
            else
                return cbi.Tag;
        }
    }
}
